Input, Ouput, Formatting Strings and Functions

Dr. Chris Gwilliams

gwilliamsc@cardiff.ac.uk

So Far and Overview

  • Output (we have covered this with the print statement
  • String formatting
  • Input (how do we get user input)
  • Casting types

  • the import keyword

  • the standard modules in Python
  • writing your own modules
  • Running scripts with command line input
  • easy_install and pip

Standard Output

The last few sessions have seen us printing to the screen like maniacs.

We have printed variables, literals and a few different types.

print("hello")
name = "Chris"
print(name)

When I introduced strings, we saw there are a few different ways to write them, the same is true for formatting a string.

Just printing a variable to the screen is a terrible idea, especially if you are using print statements to debug your code


In [2]:
name = "bob"
print(name)
name * 5
print(name)
print(name * 10) #This output is kinda useless, right?


bob
bob
bobbobbobbobbobbobbobbobbobbob

In [4]:
name = 11
print("Name is equal to " + str(name))
print("Something about: ")
print(name)
name *= 5
print("Name has been multiplied by 5 and is now equal to " + name) #slightly more informative


Name is equal to 11
Something about: 
11
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-ed3770a66c3e> in <module>()
      4 print(name)
      5 name *= 5
----> 6 print("Name has been multiplied by 5 and is now equal to " + name) #slightly more informative

TypeError: cannot concatenate 'str' and 'int' objects

A bit of a contrived example but you can see how this is useful

Exercise

Try writing the above example with a variable with the value 11

What happens?

Functions

We have seen these a lot in the course so far.

Every time you print something or want to find out the type of a variable, these are all functions built into the standard library in Python.

Exercise

Give me 4 examples of functions in Python

Writing Your Own Function:

def method_name(argument0, argument1):
    variable_inside_method = "I am indented, so I am part of the function"
    return variable_inside_method
  • def is the keyword used to define the start of a declaration
  • the name follows it and make sure it conforms to what the method does
  • the arguments of the method go inside the brackets
  • NOTE THE COLON AT THE END OF THE LINE!!
  • ALL code that is part of the method needs to be indented
  • Once a method has run, we can return a value, but we do not have to!

In [4]:
def return_a_sum(arg0, arg1):
    return arg0 + arg1


returned_variable = return_a_sum(40, 2) #call the function here and return something
print(returned_variable)


42

Methods

Methods are functions that are attached to objects. While we call a function like this:

function(argument1, argument2)

Methods are called like this:

object.method(argument1, argument2)

Objects in Python have methods attached to them that you can use. Let's learn about methods attached to strings!

What is the name of the function in Python that lists the methods attached to an object?

String Formatting

Creating a string like this:

bit_to_add = "something else"
my_string = "something something " + bit_to_add + " blah blah blah"

This is the more basic way of handling strings and it means we have to deal with different types (that we will cover later in the session)

.format

Python now has support to do something commonly known as string formatting.

Format is a method (we will learn about these as a concept later) built into the string type that allows you to specify what it contains.


In [2]:
print("My name is {}".format('Fred'))
print("My name is {} {}".format(4, 'Terry'))
print("My name is {0}".format(True)) # format does not care about types


My name is Fred
My name is 4 Terry
My name is True

Zero-Index

The 0 in the curly braces refers to the number of arguments for the format method. How many arguments do you see in the format method?

Many languages start at a zero index, this means that when you have 10 elements, their index ranges from 0 to 9. (We will see this in more detail when we come to lists in Python)

INDEX:    0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 
ELEMENT: "a"|"b"|"c"|"d"|"e"|"f"|"g"|"h"|"i"|"j"|

Exercise

"Never {0} give you {1}, Never {2} let you {3}".format("gonna", "up", "gonna", "down")

  • How many arguments are in the formatted string method above?
  • What is the index of the last argument?
  • Do you think this could be written better?

In [ ]:
`"Never {0} give you {1}, Never {0} let you {2}".format("gonna", "up", "down")`

We can reuse arguments by referring to their index here!

Exercise

Given the following string and arguments, complete the format method so they match the famous MeatLoaf song.

Note: You do not have to use all of the arguments!

I would {0} {1} for {2} but I won't {0} {3}

  • climb - anything
  • swim
  • drive
  • Everest
  • that
  • do
  • sleep
  • kill
  • truck
  • something
  • eat
  • anything

Methods vs Functions

We have introduced both methods and functions so far, and we will cover them in more detail as the course progresses, but what is the difference?

Functions are blocks of code to perform some operations and provide an output

Methods are attached to objects

Exercise

Which of the calls below are methods or functions? Write what each of these methods does in one line.


In [ ]:
my_string = "Super Cool Words"
print(len(my_string))
print("super cool {0}".format("words"))
print(my_string.lower())
print(type(my_string))
print(my_string.upper())
print(int(my_string))
  • function
  • method
  • method
  • function
  • method
  • function

Casting Types

We can instantiate a variable to be of a particular type, and we can change the type by changing the value assigned, like so:


In [8]:
pet_name = "Mr. Woofington"
print("Hello " + pet_name)
pet_name = 14055
print("Hello " + pet_name) #Why is this?


Hello Mr. Woofington
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-8-c08c341acf5b> in <module>()
      2 print("Hello " + pet_name)
      3 pet_name = 14055
----> 4 print("Hello " + pet_name) #Why is this?

TypeError: cannot concatenate 'str' and 'int' objects

Checking types

We can use the built in type function to check what type a value is:


In [ ]:
print(type(1))
print(type("what am I?"))
print(type(True))

Casting Types

Using built in functions, we can convert values from one type to another.


In [ ]:
print(str(1)) #convert int to string
print(int(True)) #bool to int
print(int("12")) #string to int

Exercise

Write a script that:

  • Prints out a request for the user's name, favourite movie and IMDb rating
  • Cast the rating to an int and turn it into a percentage
  • Print a formatted string that tells the user what their percentage is
  • If the rating is more than 70%: print out 'We have a winner'
  • If it is between 50 and 70: print out 'Not bad'
  • If it is between 30 and 50: print out 'Not a hit'
  • If it less than 30: print out 'Rotten tomato'

Exercise

  • Write a function that takes a string as an input and returns the string in all upper case
  • Call the function with different strings and print the result
  • What happens when you pass an integer as the argument?
  • Modify the function so it can handle arguments of different types

Scope

Scope defines where we are in our program and what variables/functions/objects etc we have access to.

This gives us local and global scope.

  • global means it can be accessed from anywehre
  • local means it can only be accessed from within the scope it was created in

In [1]:
global_var = "I am a global variable"

def a_function():
    local_var = "I am local"
    print(local_var)
    
a_function()
print(global_var)
print(local_var) # What happens here?


I am local
I am a global variable
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-76714db6c871> in <module>()
      7 a_function()
      8 print(global_var)
----> 9 print(local_var) # What happens here?

NameError: name 'local_var' is not defined

Scope

local_var was created within the scope of a_function and was not in the global scope, so it could not be printed.

Exercise

  • Write a function that delcares a variable within it
  • Return the variable from the function and assign it to a global variable
  • Print the global variable

Now you have changed the scope of a variable from local to global


In [ ]:
def func():
    local = "I am local"
    return(local)
global_var = func()
print(global_var)

In [9]:
age = 200

def change_age():
    age = "test"
print(age)
change_age()
print(age) #What should this equal?


200
200

Scope

This is a practical example of local scope vesus global scope. age is a global variable that has the value: 200.

Within the change_age function, a new variable, also called age, is created that is only within the local scope.

How do we access the global variable within a function?


In [10]:
age = 200

def change_age():
    global age
    age = "test"
    
print(age)
change_age()
print(age)

def change_age_no_glob(age):
    age = "test"
    return age

age = change_age_no_glob(age)


200
test

global

The global keyword allows you to use variables in the global scope inside the scope of a function. global is an excellent way to showcase scope.

Note: This is a feature that is primarily unique to Python (and PHP)

Another Example


In [7]:
def function_to_do_stuff():
    g_var = "Hello"
    
function_to_do_stuff()
print(g_var)


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-eebb57f69b25> in <module>()
      3 
      4 function_to_do_stuff()
----> 5 print(g_var)

NameError: name 'g_var' is not defined

In [8]:
def function_to_do_stuff():
    global g_var # makes new variable available in global scope
    g_var = "Hello"
    
function_to_do_stuff()
print(g_var)


Hello

Homework

Complete the 5_Homework exercise